package com.edu.compile.parse;

import com.edu.compile.Parser;
import com.edu.compile.TemplateModel;
import com.edu.compile.util.Tools;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.StringWriter;

@Component("templateParser")
public class FreemarkerParser implements Parser<TemplateModel, String> {

    private static final Logger LOGGER = LoggerFactory.getLogger(FreemarkerParser.class);

    public static final String TEMPLATE_SUFFIX = ".ftl";
    public static final String TEMPLATE_PATH = "template/ftl/";

    private Configuration configuration;

    @PostConstruct
    public void init() {
        try {
            configuration = new Configuration(Configuration.VERSION_2_3_28);
            ClassPathResource resource = new ClassPathResource(TEMPLATE_PATH);
            configuration.setDirectoryForTemplateLoading(resource.getFile());
        } catch (IOException e) {
            LOGGER.error("freemarker init failed: {}", e.getMessage());
        }
    }

    @Override
    public String parse(TemplateModel parseModel) {
        try (StringWriter writer = new StringWriter()) {
            LOGGER.info("Freemarker parse {} ", parseModel.getClass());
            Template template = configuration.getTemplate(parseModel.getTemplateName().concat(TEMPLATE_SUFFIX));
            template.process(Tools.beanToMap(parseModel), writer);
            writer.flush();
            String code = writer.toString();
            System.out.println(code);
            return code;
        } catch (IOException | TemplateException e) {
            LOGGER.error("Freemarker parse error: {}", e.getMessage());
            throw new IllegalArgumentException(e.getMessage());
        }
    }
}
